//
//  XSDataSaveManager.m
//  XSDownloadDemo
//
//  Created by 大帅 on 2023/12/21.
//

#import "XSDataSaveManager.h"

@implementation XSDataSaveManager

static XSDataSaveManager *_sharedSingleton = nil;

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 不能再使用 alloc 方法
        // 因为已经重写了 allocWithZone 方法，所以这里要调用父类的分配空间的方法
        _sharedSingleton = [[super allocWithZone:NULL] init];
    });
    return _sharedSingleton;
}

// 防止 [[A alloc] init] 和 new 引起的错误。因为 [[A alloc] init] 和 new 实际是一样的工作原理，都是执行了下面方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [XSDataSaveManager sharedManager];
}

// NSCopying 防止 copy 引起的错误。当你的单例类不遵循 NSCopying 协议，外部调用本身就会出错.
- (id)copyWithZone:(nullable NSZone *)zone {
    return [XSDataSaveManager sharedManager];
}

// 防止 mutableCopy 引起的错误，当你的单例类不遵循 NSMutableCopying 协议，外部调用本身就会出错.
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
    return [XSDataSaveManager sharedManager];
}

-(instancetype)init {
    if (self = [super init]) {
        // 建表
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        if (![[JQFMDB shareDatabase:@"XSUserDownloadVideo.sqlite" path:path] jq_isExistTable:XS_USER_DOWNLOAD_TABLE]) {
            [[JQFMDB shareDatabase:@"XSUserDownloadVideo.sqlite" path:path] jq_createTable:XS_USER_DOWNLOAD_TABLE dicOrModel:[XSTestModel class]];
            NSLog(@"建表成功");
        }
    }
    return self;
}

/// 新增一条数据
- (void)addDownloadSingleData:(XSTestModel *)model {
    // 线程安全操作
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        [[JQFMDB shareDatabase] jq_insertTable:XS_USER_DOWNLOAD_TABLE dicOrModel:model];
    }];
}

/// 新增多条数据
- (void)addDownloadMoreData:(NSArray *)list {
    // 线程安全操作
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        [[JQFMDB shareDatabase] jq_insertTable:XS_USER_DOWNLOAD_TABLE dicOrModelArray:list];
    }];
}

/// 删除指定数据
- (BOOL)deleteDownloadSingleData:(XSTestModel *)model {
    // 线程安全操作
    __block BOOL isFinish = NO;
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        // 清除指定数据本地缓存
        [[NSFileManager defaultManager] removeItemAtPath:model.localUrl error:nil];
        //删除指定一条数据
        isFinish = [[JQFMDB shareDatabase] jq_deleteTable:XS_USER_DOWNLOAD_TABLE whereFormat:[NSString stringWithFormat:@"WHERE videoId = %@", model.videoId]];
    }];
    return isFinish;
}

/// 删除指定数据（M3u8）
- (BOOL)deleteM3u8DownloadSingleData:(XSTestModel *)model {
    // 线程安全操作
    __block BOOL isFinish = NO;
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        // 清除指定数据本地缓存
        [SJMediaCacheServer.shared removeExportAssetWithURL:[NSURL URLWithString:model.url]];
        [SJMediaCacheServer.shared removeCacheForURL:[NSURL URLWithString:model.url]];
        //删除指定一条数据
        isFinish = [[JQFMDB shareDatabase] jq_deleteTable:XS_USER_DOWNLOAD_TABLE whereFormat:[NSString stringWithFormat:@"WHERE videoId = %@", model.videoId]];
    }];
    return isFinish;
}

/// 批量删除数据
- (BOOL)deleteDownloadAllData:(NSArray *)delList {
    // 线程安全操作
    [delList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        [[JQFMDB shareDatabase] jq_inDatabase:^{
            [[JQFMDB shareDatabase] jq_deleteTable:XS_USER_DOWNLOAD_TABLE whereFormat:[NSString stringWithFormat:@"WHERE videoId = %@", model.videoId]];
        }];
    }];
    return YES;
}

/// 删除全部数据
- (void)deleteDownloadAllData {
    // 线程安全操作
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        NSArray *arr = [self lookDownloadAllData];
        if (arr.count > 0) {
            // 清除本地缓存视频的文件夹
            XSTestModel *model = arr.firstObject;
            [[NSFileManager defaultManager] removeItemAtPath:model.localFolder error:nil];
        }
        // 删除全部数据
        [[JQFMDB shareDatabase] jq_deleteAllDataFromTable:XS_USER_DOWNLOAD_TABLE];
    }];
}

/// 修改指定数据
- (void)updateDownloadSingleData:(XSTestModel *)model {
    // 线程安全操作
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        [[JQFMDB shareDatabase] jq_updateTable:XS_USER_DOWNLOAD_TABLE dicOrModel:model whereFormat:[NSString stringWithFormat:@"WHERE videoId = %@", model.videoId]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 数据修改更新UI(Mp4)
            [[NSNotificationCenter defaultCenter] postNotificationName:XSDownloadMp4StateNotification object:model];
            // 数据修改更新UI(m3u8)
            [[NSNotificationCenter defaultCenter] postNotificationName:XSDownloadM3u8StateNotification object:model];
        });
    }];
}

/// 查看指定数据
- (XSTestModel *)lookDownloadSingleData:(XSTestModel *)model {
    __block NSArray *tempArr = nil;
    // 线程安全操作
    [[JQFMDB shareDatabase] jq_inDatabase:^{
        tempArr = [[JQFMDB shareDatabase] jq_lookupTable:XS_USER_DOWNLOAD_TABLE dicOrModel:XSTestModel.class whereFormat:[NSString stringWithFormat:@"WHERE videoId = %@", model.videoId]];
    }];
    return tempArr.firstObject;
}

/// 查看全部数据
- (NSArray *)lookDownloadAllData {
    __block NSArray *tempArr = nil;
    @synchronized (self) {
        // 线程安全操作
        [[JQFMDB shareDatabase] jq_inDatabase:^{
            tempArr = [[JQFMDB shareDatabase] jq_lookupTable:XS_USER_DOWNLOAD_TABLE dicOrModel:XSTestModel.class whereFormat:nil];
        }];
        return tempArr;
    }
}

@end
